from functools import partial

from pywebio3.input import *
from pywebio3.output import *


def add_student():
    with use_scope("data", clear=True):
        user_dict = input_group(
            "学生信息",
            [
                input("学号：", name="id"),
                input("姓名：", name="name"),
                input("年龄：", name="age"),
            ]
        )
        index = len(students)
        students.append([
            user_dict["id"], user_dict["name"], user_dict["age"],
            put_buttons(['编辑', "删除"], onclick=partial(update_student, index=index)),
        ])
    show_students()


def update_student(btn, index):
    if btn == "删除":
        del students[index]
        show_students()
        return

    student = students[index]
    with use_scope("data", clear=True):
        user_dict = input_group(
            "学生信息",
            [
                input("学号：", name="id", value=student[0]),
                input("姓名：", name="name", value=student[1]),
                input("年龄：", name="age", value=student[2]),
            ]
        )
        students[index] = [
            user_dict["id"],
            user_dict["name"],
            user_dict["age"],
            put_buttons(
                ['编辑', "删除"],
                onclick=partial(update_student, index=index),
            ),
        ]
    show_students()


def show_students():
    with use_scope("data", clear=True):
        put_buttons(["新增"], onclick=[add_student])
        put_table([
            ["学号", "姓名", "年龄", "操作"],
            *students,
        ])


if __name__ == '__main__':
    students = [
        ["2024121501", "张三", 22, put_buttons(['编辑', "删除"], onclick=partial(update_student, index=0))],
        ["2024121502", "李四", 21, put_buttons(['编辑', "删除"], onclick=partial(update_student, index=1))],
        ["2024121503", "王五", 22, put_buttons(['编辑', "删除"], onclick=partial(update_student, index=0))],
    ]
    show_students()
